package com.facishare.open.controller;

import com.facishare.open.ajax.code.AjaxCode;
import com.facishare.open.ajax.result.AjaxResult;
import com.facishare.open.common.result.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;


@Slf4j
public abstract class BaseController {

    protected static final AjaxResult SUCCESS = new AjaxResult(null);
    protected void checkParam(Object obj, String message) {
        if (null == obj) {
            throw new BizException(AjaxCode.PARAM_ERROR, message);
        }

        if (obj instanceof String && StringUtils.isBlank((String) obj)) {
            throw new BizException(AjaxCode.PARAM_ERROR, message);
        }
    }

    protected void checkParam(String obj, String regex, String message) {
        checkParam(obj, message);
        if (null != regex && !obj.matches(regex)) {
            throw new BizException(AjaxCode.PARAM_ERROR, message);
        }
    }

    /**
     * 异常通用处理
     *
     * @param request
     * @param e
     * @throws Exception
     */
    @ExceptionHandler
    @ResponseBody
    public AjaxResult exception(HttpServletRequest request, Exception e) throws Exception {
        log.error("req[" + request.getRequestURI() + "]异常信息：" + e.getLocalizedMessage(), e);
        if (e instanceof HttpMessageNotReadableException) {
            return new AjaxResult(AjaxCode.BIZ_EXCEPTION, "系统异常:" + e.getLocalizedMessage());
        }
        if (e instanceof BizException) {
            BizException biz = (BizException) e;
            if (AjaxCode.USER_NOT_LOGIN == biz.getErrCode()){
                return new AjaxResult(biz.getErrCode(), biz.getErrDescription());
            }
            return new AjaxResult(biz.getErrCode(), biz.getErrDescription());
        }
        return new AjaxResult(AjaxCode.BIZ_EXCEPTION, "系统异常");
    }
}
